package com.example.hw01.servlet;

import com.example.hw01.model.CartItem;
import com.example.hw01.model.Product;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "CartServlet", value = "/cart")
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查用户是否登录
        HttpSession session = request.getSession();
        if (session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 显示购物车页面
        request.getRequestDispatcher("cart.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查用户是否登录
        HttpSession session = request.getSession();
        if (session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        String action = request.getParameter("action");
        if (action != null) {
            switch (action) {
                case "add":
                    addToCart(request, response);
                    break;
                case "update":
                    updateCartItem(request, response);
                    break;
                case "remove":
                    removeFromCart(request, response);
                    break;
                case "clear":
                    clearCart(request, response);
                    break;
            }
        }
        response.sendRedirect("cart");
    }

    private void addToCart(HttpServletRequest request, HttpServletResponse response) {
        try {
            int productId = Integer.parseInt(request.getParameter("productId"));
            int quantity = Integer.parseInt(request.getParameter("quantity"));

            if (quantity <= 0) {
                request.setAttribute("error", "数量必须大于0");
                return;
            }

            HttpSession session = request.getSession();
            List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
            if (cart == null) {
                cart = new ArrayList<>();
                session.setAttribute("cart", cart);
            }

            // 获取商品列表
            List<Product> products = (List<Product>) getServletContext().getAttribute("products");
            Product product = products.stream()
                    .filter(p -> p.getId() == productId)
                    .findFirst()
                    .orElse(null);

            if (product != null) {
                // 检查是否已存在该商品
                boolean exists = false;
                for (CartItem item : cart) {
                    if (item.getProduct().getId() == productId) {
                        item.setQuantity(item.getQuantity() + quantity);
                        exists = true;
                        break;
                    }
                }

                if (!exists) {
                    cart.add(new CartItem(product, quantity));
                }

                // 减少库存
                product.setStock(product.getStock() - quantity);
                request.setAttribute("message", "商品已添加到购物车");
            }
        } catch (NumberFormatException e) {
            request.setAttribute("error", "参数错误");
        }
    }

    private void updateCartItem(HttpServletRequest request, HttpServletResponse response) {
        try {
            int productId = Integer.parseInt(request.getParameter("productId"));
            int newQuantity = Integer.parseInt(request.getParameter("quantity"));

            if (newQuantity <= 0) {
                request.setAttribute("error", "数量必须大于0");
                return;
            }

            HttpSession session = request.getSession();
            List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
            if (cart != null) {
                for (CartItem item : cart) {
                    if (item.getProduct().getId() == productId) {
                        // 计算库存变化
                        int quantityChange = newQuantity - item.getQuantity();

                        // 检查库存是否足够
                        if (item.getProduct().getStock() >= quantityChange) {
                            item.setQuantity(newQuantity);
                            item.getProduct().setStock(item.getProduct().getStock() - quantityChange);
                            request.setAttribute("message", "购物车已更新");
                        } else {
                            request.setAttribute("error", "库存不足");
                        }
                        break;
                    }
                }
            }
        } catch (NumberFormatException e) {
            request.setAttribute("error", "参数错误");
        }
    }

    private void removeFromCart(HttpServletRequest request, HttpServletResponse response) {
        try {
            int productId = Integer.parseInt(request.getParameter("productId"));

            HttpSession session = request.getSession();
            List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
            if (cart != null) {
                for (CartItem item : cart) {
                    if (item.getProduct().getId() == productId) {
                        // 恢复库存
                        item.getProduct().setStock(item.getProduct().getStock() + item.getQuantity());
                        cart.remove(item);
                        request.setAttribute("message", "商品已从购物车移除");
                        break;
                    }
                }
            }
        } catch (NumberFormatException e) {
            request.setAttribute("error", "参数错误");
        }
    }

    private void clearCart(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
        if (cart != null) {
            // 恢复所有商品库存
            for (CartItem item : cart) {
                item.getProduct().setStock(item.getProduct().getStock() + item.getQuantity());
            }
            cart.clear();
            request.setAttribute("message", "购物车已清空");
        }
    }
}